package com.itydl.a05;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;

import com.itydl.a05.view.RefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author ydl
 * @version
 */

public class TestActivity extends AppCompatActivity implements RefreshListView.OnRefreshListener {

    private static final int REFRESH_COMPLETE = 0;
    private RefreshListView mListView;
    private ArrayList<String> mDatas;

    /**
     * MyHandler是一个私有静态内部类继承自Handler，内部持有MainActivity的弱引用，
     * 避免内存泄露
     */
    private MyHandler mHandler = new MyHandler(this);

    private ArrayAdapter<String> mAdapter;

    private static class MyHandler extends Handler{

        private WeakReference<TestActivity> mActivity;
        public MyHandler(TestActivity activity){
            mActivity = new WeakReference<TestActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            TestActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case REFRESH_COMPLETE:
                        activity.mListView.setOnRefreshComplete();
                        activity.mAdapter.notifyDataSetChanged();
                        activity.mListView.setSelection(0);
                        break;
                }
            }else{
                super.handleMessage(msg);
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        mListView = (RefreshListView) findViewById(R.id.lv_refresh);
        mDatas = new ArrayList<String>(Arrays.asList(Strings.NAMES));
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mDatas);
        mListView.setAdapter(mAdapter);
        mListView.setOnRefreshListener(this);
    }

    @Override
    public void onRefreshing() {
        //开启子线程访问网络
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                mDatas.add(0, "new data");
                mHandler.sendEmptyMessage(REFRESH_COMPLETE);
            }
        }).start();
    }

}
